package com.example.study_manger.tools;

import com.sun.jdi.event.ExceptionEvent;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthInterceptor implements HandlerInterceptor {

    // 请求之前进行认证
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/user/") || requestURI.startsWith("/api/")) {
            return true;
        }
        String token = request.getHeader("token");  // 从请求头中获取 token
        System.out.println(token);
        try {
            if (token == null || token.isEmpty()) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  // 无token时返回401
                return false;
            }

            // Token 校验逻辑，例如解析 token 并验证其有效性
            JwtUtil.verifyToken(token);  // 这里使用你自己的方法来验证JWT
            return true;
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  // token验证失败
            response.getWriter().write("Unauthorized access");
            return false;
        }
    }
}
